package org.example.maven.utils.Date;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpUtils {
    private static final int MAX_RETRIES = 3;      // 最大重试次数
    private static final int RETRY_DELAY_MS = 2000; // 每次重试间隔（毫秒）

    public static String sendGet(String urlStr) {
        for (int i = 0; i < MAX_RETRIES; i++) {
            try {
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    return response.toString();
                } else if (responseCode == 429) {
                    System.out.println("收到 429 响应，正在重试...");
                    Thread.sleep(RETRY_DELAY_MS); // 等待后重试
                } else {
                    System.err.println("请求失败，响应码: " + responseCode);
                    return "";
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
        System.err.println("超过最大重试次数，放弃请求");
        return "";
    }
}


